package com.lovo.pz.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.sound.sampled.*;


/**
 * 此类为音乐类,用于播放各种音乐
 */
public class GameMusic extends Thread {

	private static Clip singleMusic;

	private static Clip loopMusic;
	public GameMusic(){}

	/**
	 * 播放单音音频
	 * @param musicFile    单音音频文件路径
	 */
	public static void playSingleMusic(String musicFile) {
		try {
			File file = new File(musicFile);
			AudioInputStream in = AudioSystem.getAudioInputStream(file);
			AudioFormat outFormat = getOutFormat(in.getFormat());
			singleMusic = AudioSystem.getClip();
			singleMusic.open(AudioSystem.getAudioInputStream(outFormat, in));
			singleMusic.start();
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}

	}

	/**
	 * 循环播放音频
	 * @param musicFile
	 */
	public static void playLoopMusic(String musicFile){
		stopLoopMusic();
		try {
			File file = new File(musicFile);
			AudioInputStream in = AudioSystem.getAudioInputStream(file);
			AudioFormat outFormat = getOutFormat(in.getFormat());
			loopMusic = AudioSystem.getClip();
			loopMusic.open(AudioSystem.getAudioInputStream(outFormat, in));
			loopMusic.start();
			loopMusic.loop(Clip.LOOP_CONTINUOUSLY);

		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	/**
	 * 停止播放循环音频
	 */
	public static void stopLoopMusic() {
		if(loopMusic != null){
			loopMusic.stop();
		}
	}

	/**
	 * 停止播放单音音频
	 *
	 */
	public static void stopSingleMusic() {
		if(singleMusic != null){
			singleMusic.stop();
		}
	}

	private static AudioFormat getOutFormat(AudioFormat inFormat) {
		final int ch = inFormat.getChannels();
		final float rate = inFormat.getSampleRate();
		return new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
	}

	public static void main(String[] args) {
		GameMusic.playSingleMusic("sounds/awooga.ogg");
//		GameMusic.playLoopMusic("sounds/awooga.ogg");
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		GameMusic.stopSingleMusic();

	}


}
